//
//  XTUserAcount.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/12.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

class XTUserAcount: NSObject {
    //用户授权的唯一票据
    var access_token:String?
    //access_token的生命周期，以秒为单位
    var expires_in :NSTimeInterval = 0 {
        didSet{
        //过期时间＝ 当前时间 ＋ 生命周期
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    
    //过期时间
    var expiresDate :  NSDate?
    
    //授权用户uid
    var uid:Int64 = 0
    
    //用户名
    var name:String?
    
    //用户头像
    var avatar_large:String?
    
    //本类的构造函数
    init(dic:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    //键值对未赋全防崩溃函数
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //重写description方法
    override var description : String{
    let keys = ["access_token","uid","name","avatar_large","expires_in"]
        return dictionaryWithValuesForKeys(keys).description
        
    }
    

        //  MARK: -归档和解档-
    
    //解档(由下面archiveRootObject被调用时自动被调用)
    func encodeWithCoder(aCoder:NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    
    // 归档编码（由下面unarchiveObjectWithFile调用时被调用）
    required init?(coder aDecoder:NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        
        uid = aDecoder.decodeInt64ForKey("uid")
        
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        
        name = aDecoder.decodeObjectForKey("name") as? String
        
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    
    //保存用户信息到文件中
    //归档
    func saveUserAccount()->Bool{
    //保存的路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
        return NSKeyedArchiver.archiveRootObject(self, toFile:path)
    
    }
    
    //解档
        //class为类方法的意思
    class func loadUserAcction ()->XTUserAcount?{
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? XTUserAcount
    }
    
}

















